# --*-- coding:utf-8 --*--
# @Time    : 2025/07/02 00:39
# @Author  : Xu
# @Email   : wsxzy98@outlook.com
# @File    : stock_package_destination.py
# @Software: VScode

from odoo import api, fields, models
from odoo.exceptions import UserError

class StockPackageDestination(models.TransientModel):
    _inherit = 'stock.package.destination'

    #wave点货功能扩展
    @api.depends('picking_id')
    def _compute_move_line_ids(self):
        move_lines_to_pack_ids = self.env.context.get('move_lines_to_pack_ids')
        batch = self.picking_id.batch_id if self.picking_id else False
        if batch:
            pickings = self.env['stock.picking'].search([('batch_id', '=', batch.id)])
            all_moves = pickings.mapped('move_ids')
        else:
            all_moves = self.picking_id.move_ids if self.picking_id else self.env['stock.move']
            
        # split 并清理脏数据
        if all_moves:
            all_moves.split_uncompleted_moves()
            
        # 筛选 move_lines_to_pack
        if move_lines_to_pack_ids:
            move_lines = self.env['stock.move.line'].browse(move_lines_to_pack_ids)
            self.move_line_ids = move_lines.filtered(lambda l: l.qty_done > 0 and not l.result_package_id)
        else:
            self.move_line_ids = self.env['stock.move.line']

    @api.onchange('location_dest_id')
    def _onchange_location_dest_id(self):
        """
        切换目标库位时，实际move_line_ids字段同步为当前库位下所有qty_done>0的明细。
        """
        if self.location_dest_id:
            # wave下所有明细，保证所有目标库位都能查到
            all_lines = self.picking_id.batch_id.move_line_ids if self.picking_id.batch_id else self.move_line_ids
            self.move_line_ids = all_lines.filtered(
                lambda l: l.location_dest_id.id == self.location_dest_id.id and l.qty_done > 0 and not l.result_package_id
            )
        else:
            # 可恢复全量，或清空
            self.move_line_ids = False

    def action_done(self):
        """
        强制允许同库位、不同picking的所有明细一起打包
        """
        move_lines = self.move_line_ids.filtered(
            lambda l: l.location_dest_id.id == self.location_dest_id.id and l.qty_done > 0 and not l.result_package_id
        )
        if not move_lines:
            raise UserError('当前没有可打包的明细！')
        
        # 自己生成包裹，不走原生picking打包校验
        package = self.env['stock.quant.package'].create({})
        move_lines.write({
            'result_package_id': package.id,
            'location_dest_id': self.location_dest_id.id,
        })
        # 按需写关联表、分组等
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
    
    def action_discard(self):
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
